package ca.uwindsor.cs.deepweb.utility.sougouweb;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;

import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.store.LockObtainFailedException;
import org.xml.sax.InputSource;

import ca.uwindsor.cs.deepweb.estimation.DictionariesFilesContentIndexer;
import ca.uwindsor.cs.deepweb.estimation.FilesContentIndexer;

/**
 * Warning: Some documents in the index created will have null termvector.
 * After indexing, you can use NullContentDocumentRemover to remove those
 * whose termvector is null.
 * @author Jie Liang
 *
 */
public class SogouXMLFilesIndexer extends DictionariesFilesContentIndexer {

	private SogouWebCorpusDocumentHandler handler;

	private InputStreamReader reader;

	private int size;

	public SogouXMLFilesIndexer(String sourcepath, String indexdir,
			String encoding, boolean verbose, boolean create, String[] ext) {
		super(sourcepath, indexdir, encoding, verbose, create, ext);
		// TODO Auto-generated constructor stub
	}

	protected void generateIndex(File dir) {
		try {
			File[] dataFiles = dir.listFiles();
			// Add documents to the index
			for (int i = 0; i < dataFiles.length; i++) {
				File file = dataFiles[i];
				if (file.isFile() && isValidExtension(file.getName())) {

					handler = new SogouWebCorpusDocumentHandler();
					try {
						reader = new InputStreamReader(
								new FileInputStream(file), "UTF-8");

						handler.processDocument(new InputSource(reader));
					} catch (Exception e) {
						System.err
								.println("Error on parsing: " + i + " file at "
										+ dataFiles[i].getCanonicalPath());
						continue;
					}

					String content = handler.getContent().replaceAll("+", "");
					size = content.length();

					if (isVerbose) {
						System.out.println("Indexing file "
								+ dataFiles[i].getCanonicalPath());
					}

					Document document = new Document();
					// make the ID from the path shorter - get the file name
					String filepath = file.getCanonicalPath();
					int offset1 = filepath.lastIndexOf(java.io.File.separator);
					int offset2 = filepath.lastIndexOf(".");
					String word = new String(filepath.substring(offset1 + 1,
							offset2));

					// String word = String.valueOf(globalID);
					// System.out.println(id);

					Field FieldPath = new Field(FilesContentIndexer.FIELD_ID,
							word, Field.Store.YES, Field.Index.UN_TOKENIZED);

					Field FieldTitle = new Field(
							FilesContentIndexer.FIELD_TITLE,
							handler.getDocID(), Field.Store.YES,
							Field.Index.UN_TOKENIZED);

					Field FieldSize = new Field(FilesContentIndexer.FIELD_SIZE,
							Integer.toString(size), Field.Store.YES,
							Field.Index.UN_TOKENIZED);

					Field FieldBody = new Field(
							FilesContentIndexer.FIELD_CONTENT, content,
							Field.Store.NO, Field.Index.TOKENIZED,
							Field.TermVector.WITH_POSITIONS_OFFSETS);

					document.add(FieldPath);
					document.add(FieldTitle);
					document.add(FieldSize);
					document.add(FieldBody);
					indexWriter.addDocument(document);
					// txtReader.close();
					globalID++;

				} else if (file.isDirectory()) {
					generateIndex(dataFiles[i]);
				}
				if (globalID == 10000000)
					break;
			}
		} catch (CorruptIndexException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.exit(1);
		} catch (LockObtainFailedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.exit(1);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.exit(1);
		}
	}

	public static void main(String[] args) {
		// String[] ext = { "html" };
		// SogouXMLFilesIndexer indexer = new SogouXMLFilesIndexer(
		// "G:/gov2-corpus-extracted", "F:/indexes/GOV2", "UTF-8", true,
		// true, ext);
		// indexer.generateIndex();

		// args = new String[7];
		// args[0] = "--SourceDir=Y:\\";
		// args[1] = "--IndexDir=F:\\indexes\\test";
		// args[2] = "--encoding=UTF-8";
		// args[3] = "-verbose";
		// args[4]= "-create";
		// args[5]= "-resursive";
		// args[6]= "--extension=xml";

		String SourceDir = new String();
		String IndexDir = new String();
		String encoding = new String("UTF-8");
		boolean isVerbose = false;
		boolean isCreate = true;

		String ext[] = new String[] { "html" };

		if (args.length < 2) {
			System.out
					.println("usage: java -jar SogouXMLFilesIndexer --SourceDir=sourcefiledirectory --IndexDir=indexfiledirectory --extension=txt,html,... [--encoding=encoding](default=UTF-8) [-verbose] [-create] !");
			System.exit(0);
		} else {
			for (int i = 0; i < args.length; i++) {
				if (args[i].startsWith("--SourceDir=")) {
					SourceDir = args[i].substring(12);
				} else if (args[i].startsWith("--IndexDir=")) {
					IndexDir = args[i].substring(11);
				} else if (args[i].startsWith("--encoding=")) {
					encoding = args[i].substring(11);
				} else if (args[i].equals("-create")) {
					isCreate = true;
				} else if (args[i].equals("-verbose")) {
					isVerbose = true;
				} else if (args[i].startsWith("--extension=")) {
					String tempexts = args[i].substring(12);
					ext = tempexts.split(",");
				}
			}
		}

		if (SourceDir.equals("") || IndexDir.equals("")) {
			System.out
					.println("usage: java -jar SogouXMLFilesIndexer SourceDir=sourcefiledirectory IndexDir=indexfiledirectory [encoding=encoding](default=UTF-8) [-verbose]!");
			System.exit(0);
		} else {
			SogouXMLFilesIndexer indexer;
			// if (isRecursive) {
			// indexer = new SogouXMLFilesIndexer(SourceDir, IndexDir, encoding,
			// isVerbose, isCreate, ext);
			// } else {
			// indexer = new SogouXMLFilesIndexer (SourceDir, IndexDir,
			// encoding,
			// isVerbose, isCreate, ext);
			// }
			indexer = new SogouXMLFilesIndexer(SourceDir, IndexDir, encoding,
					isVerbose, isCreate, ext);
			indexer.generateIndex();
		}

	}
}
